import { DynamicModule, Global, Module } from "@nestjs/common";
import { NatsClientService } from "./nats-client.service";
import { ClientProxy, ClientsModule, Transport } from "@nestjs/microservices";
import { configuration } from "../../../config/config";

@Global()
export class NatsClientModule {
  constructor(
  ) {
  }
  static forRoot(natsClientName: string): DynamicModule {
    console.log(
      `向NATS 注册服务： ${natsClientName}, 注册的服务器地址为：${configuration.natsServer}`,
    );
    return {
      global: true,
      imports: [
        ClientsModule.register([
          {
            name: natsClientName,
            transport: Transport.NATS,
            options: {
              servers: configuration.natsServer,
            },
          },
        ]),
      ],
      module: NatsClientModule,
      providers: [
        {
          provide: NatsClientService,
          useFactory: (natsClientName) =>{
            return  new NatsClientService(natsClientName)
          },
          inject: [natsClientName],
        },
      ],
      exports: [NatsClientService, ClientsModule],
    };
  }
}
